<?php

namespace app\admin\controller\questionnaire\config;

use app\BaseController;
use app\model\questionnaire\QuestionnaireLabelModel;
use app\model\questionnaire\QuestionnaireTopicAnswerModel;
use app\model\questionnaire\QuestionnaireTopicImgModel;
use app\model\questionnaire\QuestionnaireTopicLabelModel;
use app\model\questionnaire\QuestionnaireTopicModel;
use app\model\UserModel;
use think\App;

class Topic extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 标签选择器
     * @return bool|string
     */
    public function labelSelector(): bool|string
    {
        try {
            $QuestionnaireLabelModel = new QuestionnaireLabelModel();
            $data = $QuestionnaireLabelModel->where('unit_id','=',$this->userData['unit_id'])
                ->withCount(['topicLabel'])->field('id,name')->select()->toArray();
            $del = [];
            foreach ($data as $key => $item){
                if ($item['topic_label_count'] == 0){
                    $del[] = $item['id'];
                    unset($data[$key]);
                }
            }
            if (!empty($del)){
                $QuestionnaireLabelModel->where('id','in',$del)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 类型选择器
     * @return bool|string
     */
    public function typeSelector(): bool|string
    {
        try {
            $data = [
                ['id' => 1, 'name' => '单选题'],
                ['id' => 2, 'name' => '多选题'],
                ['id' => 3, 'name' => '填空题'],
                ['id' => 4, 'name' => '判断题'],
                ['id' => 5, 'name' => '问答题'],
            ];
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 题目类型配置
     * @param int $type
     * @return string
     */
    public function typeConfig(int $type): string
    {
        //题目类型【1单选，2多选，3填空，4判断，5 问答题】
        return match ($type){
            1 => '单选题',
            2 => '多选题',
            3 => '填空题',
            4 => '判断题',
            5 => '问答题',
            default => ''
        };
    }

    /**
     * 编辑人选择器
     * @return bool|string
     */
    public function editorSelector(): bool|string
    {
        try {
            $QuestionnaireTopicModel = new QuestionnaireTopicModel();
            $UserModel = new UserModel();
            $uid = $QuestionnaireTopicModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['status','=',1]
            ])->column('uid');
            $data = $UserModel->where('id','in',$uid)->field('id,name')->select();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 分数选择器
     * @return bool|string
     */
    public function scoreSelector(): bool|string
    {
        try {
            $QuestionnaireTopicModel = new QuestionnaireTopicModel();
            $data = $QuestionnaireTopicModel->where([
                ['unit_id','=',$this->userData['unit_id']],
                ['status','=',1]
            ])->distinct(true)->column('score');
            sort($data);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 题库列表
     * @return bool|string
     */
    public function list(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize' => 'require|integer',
            ]);
            $where = [];
            if (!empty($param['content'])){
                $where[] = ['content','like','%'.$param['content'].'%'];
            }
            if (!empty($param['label'])) {
                $QuestionnaireLabelModel = new QuestionnaireLabelModel();
                $label_id = $QuestionnaireLabelModel->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['name','in',$param['label']]
                ])->column('id');
                $QuestionnaireTopicLabelModel = new QuestionnaireTopicLabelModel();
                $topic_id = $QuestionnaireTopicLabelModel->where('label_id','in',$label_id)->column('topic_id');
                if (count($topic_id) > 0) {
                    $where[] = ['id','in',$topic_id];
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            if (!empty($param['type'])) {
                $where[] = ['type','=',$param['type']];
            }
            if (!empty($param['uid'])) {
                $where[] = ['uid','=',$param['uid']];
            }
            if (!empty($param['score'])) {
                $where[] = ['score','=',$param['score']];
            }
            $where[] = ['status','=',1];
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $QuestionnaireTopicModel = new QuestionnaireTopicModel();
            $query = $QuestionnaireTopicModel->where($where);
            $data = $query->with([
                'user',
                'label' => function ($query) {
                    $query->with(['labelName']);
                },
                'answer'
            ])->paginate($param['pageSize'])->toArray();
//            foreach ($data['data'] as &$item) {
//                $item['type'] = $this->typeConfig($item['type']);
//            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 题目详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $QuestionnaireTopicModel = new QuestionnaireTopicModel();
            $info = $QuestionnaireTopicModel->with([
                'label' => function ($query) {
                    $query->with(['labelName']);
                },
                'img',
                'answer'])->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            foreach ($info['answer'] as &$item) {
                $item['num'] = 'index'.$item['num'];
            }
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 题库添加
     * @return bool|string
     */
    public function add(): bool|string
    {
        $QuestionnaireTopicModel = new QuestionnaireTopicModel();
        $QuestionnaireTopicModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'type|类型' => 'require|integer',
                'score|得分' => 'require|integer',
                'content|题目内容' => 'require',
                'answer|答案选项' => 'require',
//                'label|标签' => 'require',
            ]);
            if ($param['type'] == 2) {
                $this->validate($param,[
                    'method|计分方式' => 'require',
                    'method_score|计分方式每题得分' => 'require',
                ]);
            }
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
//            $param['status'] = 1;
            $param['up_time'] = $param['time'] = time();
            //题目图片
            if(!empty($param['img'])){
                foreach ($param['img'] as $img){
                    $imgData[] = [
                        'img' => $img['img'],
                        'time' => $param['time'],
                    ];
                }
                unset($param['img']);
            }
            //答案选项
            if (!empty($param['answer'])) {
                $answerStatus = array_column($param['answer'], 'status');
                if(in_array($param['type'],[1,2,4]) && !in_array(1,$answerStatus)) throw new \Exception('必须选择一个为答案！');
                foreach ($param['answer'] as $answer){
                    if (empty($answer['name'])) throw new \Exception('答案不能为空！');
                    $answerData[] = [
                        'name' => $answer['name'],
                        'num' => intval(str_replace('index','',$answer['num'])),
                        'score' => $answer['score'],
                        'status' => $answer['status'],
                        'time' => $param['time'],
                    ];
                }
                unset($param['answer']);
            }
            //标签
            if (!empty($param['label'])) {
                $QuestionnaireLabelModel = new QuestionnaireLabelModel();
                foreach ($param['label'] as $label){
                    $label_id = $QuestionnaireLabelModel->where([
                        ['unit_id','=',$this->userData['unit_id']],
                        ['name','in',$label['name']]
                    ])->value('id');
                    if (!$label_id){
                        $label_id = $QuestionnaireLabelModel->insertGetId([
                            'unit_id' => $this->userData['unit_id'],
                            'name' => $label['name'],
                            'time' => time()
                        ]);
                    }
                    $labelAdd = [
                        'unit_id' => $this->userData['unit_id'],
                        'label_id' => $label_id,
                        'time' => $param['time'],
                    ];
                    if (!empty($label['id'])){
                        $labelAdd['id'] = $label['id'];
                    }
                    $labelData[] = $labelAdd;
                }
                unset($param['label']);
            }
            $topic_id = $QuestionnaireTopicModel->insertGetId($param);
            if (!empty($imgData)){
                foreach ($imgData as &$img){
                    $img['topic_id'] = $topic_id;
                }
                $QuestionnaireTopicImgModel = new QuestionnaireTopicImgModel();
                $QuestionnaireTopicImgModel->insertAll($imgData);
            }
            if (!empty($answerData)){
                foreach ($answerData as &$answer){
                    $answer['topic_id'] = $topic_id;
                }
                $QuestionnaireTopicAnswerModel = new QuestionnaireTopicAnswerModel();
                $QuestionnaireTopicAnswerModel->insertAll($answerData);
            }
            if (!empty($labelData)){
                foreach ($labelData as &$label){
                    $label['topic_id'] = $topic_id;
                }
                $QuestionnaireTopicLabelModel = new QuestionnaireTopicLabelModel();
                $QuestionnaireTopicLabelModel->saveAll($labelData);
            }
            $QuestionnaireTopicModel->commit();
            return success([
                'topic_id' => $topic_id
            ]);
        } catch (\Exception $e) {
            $QuestionnaireTopicModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 题库编辑
     * @return bool|string
     */
    public function update(): bool|string
    {
        $QuestionnaireTopicModel = new QuestionnaireTopicModel();
        $QuestionnaireTopicModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
                'type|类型' => 'require|integer',
                'score|得分' => 'require|integer',
                'content|题目内容' => 'require',
                'answer|答案选项' => 'require',
//                'label|标签' => 'require',
            ]);
            $info = $QuestionnaireTopicModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if ($param['type'] == 2) {
                $this->validate($param,[
                    'method|计分方式' => 'require',
                    'method_score|计分方式每题得分' => 'require',
                ]);
            }
            $QuestionnaireTopicImgModel = new QuestionnaireTopicImgModel();
            $QuestionnaireTopicAnswerModel = new QuestionnaireTopicAnswerModel();
            $QuestionnaireTopicLabelModel = new QuestionnaireTopicLabelModel();
            $param['up_time'] = time();
            //删除图片
            if (!empty($param['img_del'])){
                $QuestionnaireTopicImgModel->where('id','in',$param['img_del'])->update([
                    'is_del' => 1,
                    'del_time' => time(),
                ]);
            }
            //删除答案选项
            if (!empty($param['answer_del'])){
                $QuestionnaireTopicAnswerModel->where('id','in',$param['answer_del'])->update([
                    'is_del' => 1,
                    'del_time' => time(),
                ]);
            }
            //删除标签
            if (!empty($param['label_del'])){
                $QuestionnaireTopicLabelModel->where('id','in',$param['label_del'])->update([
                    'is_del' => 1,
                    'del_time' => time(),
                ]);
            }
            //题目图片
            if(!empty($param['img'])){
                $imgData = [];
                foreach ($param['img'] as $img){
                    if (empty($img['id'])){
                        $img['topic_id'] = $param['id'];
                        $img['time'] = time();
                    }
                    $imgData[] = $img;
                }
                $QuestionnaireTopicImgModel->saveAll($imgData);
                unset($param['img']);
            }
            //答案选项
            if (!empty($param['answer'])) {
                $answerStatus = array_column($param['answer'], 'status');
                if(in_array($param['type'],[1,2,4]) && !in_array(1,$answerStatus)) throw new \Exception('必须选择一个为答案！');
                $answerData = [];
                foreach ($param['answer'] as $answer){
                    if (empty($answer['name'])) throw new \Exception('答案不能为空！');
                    if (empty($answer['id'])){
                        $answer['topic_id'] = $param['id'];
                        $answer['time'] = time();
                    }
                    $answer['num'] = intval(str_replace('index','',$answer['num']));
                    $answerData[] = $answer;
                }
                $QuestionnaireTopicAnswerModel->saveAll($answerData);
                unset($param['answer']);
            }
            //标签
            if (!empty($param['label'])) {
                $labelData = [];
                $QuestionnaireLabelModel = new QuestionnaireLabelModel();
                foreach ($param['label'] as $label){
                    $label_id = $QuestionnaireLabelModel->where([
                        ['unit_id','=',$this->userData['unit_id']],
                        ['name','in',$label['name']]
                    ])->value('id');
                    if (!$label_id){
                        $label_id = $QuestionnaireLabelModel->insertGetId([
                            'unit_id' => $this->userData['unit_id'],
                            'name' => $label['name'],
                            'time' => time()
                        ]);
                    }
                    $labelAdd = [
                        'unit_id' => $this->userData['unit_id'],
                        'topic_id' => $param['id'],
                        'label_id' => $label_id,
                        'time' => time(),
                    ];
                    if (!empty($label['id'])){
                        $labelAdd['id'] = $label['id'];
                    }
                    $labelData[] = $labelAdd;
                }
                $QuestionnaireTopicLabelModel->saveAll($labelData);
                unset($param['label']);
            }
            $info->save($param);
            $QuestionnaireTopicModel->commit();
            return success([
                'topic_id' => $param['id']
            ],'编辑成功！');
        } catch (\Exception $e) {
            $QuestionnaireTopicModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 题库删除
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $QuestionnaireTopicModel = new QuestionnaireTopicModel();
            if (is_array($id)){
                $QuestionnaireTopicModel->where('id','in',$id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }else{
                $QuestionnaireTopicModel->where('id',$id)->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success([],'删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
}